package dice.sinanya.db.redis;

import dice.sinanya.db.tools.JedisUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.Set;

import static dice.sinanya.system.MessagesSystem.loginInfo;

public class LiveBot {
    private static final Logger logger = LogManager.getLogger(LiveBot.class.getName());

    public static void updateLive() {
        try (Jedis jedis = JedisUtil.getJedis(15)) {
            String qqId = String.valueOf(loginInfo.getLoginId());
            jedis.set(qqId, "");
            jedis.expire(qqId, 9);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    public static void offLiveForHeat() {
        try (Jedis jedis = JedisUtil.getJedis(16)) {
            String qqId = String.valueOf(loginInfo.getLoginId());
            jedis.set(qqId, "off");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    public static void checkUnLiveBot() {
        ArrayList<String> botLiveList;
        try (Jedis jedis = JedisUtil.getJedis(15)) {
            botLiveList = new ArrayList<>(jedis.keys("*"));
        }

        try (Jedis jedis = JedisUtil.getJedis(5)) {
            Set<String> groupList = jedis.keys("*");
            for (String group : groupList) {
                String qqId = "";
                try {
                    qqId = jedis.hget(group, "botId");
                } catch (Exception e) {
                    jedis.del(group);
                }
                if (!botLiveList.contains(qqId)) {
                    jedis.del(group);
                }
            }
        }
    }
}
